#include "WordPack.h"
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>

using std::cout;
using std::cin;
using std::endl;
using std::fstream;

WordPack::WordPack(std::string fileName)
{
	char isBin[4];
	std::string testStr = "bin";
	ioFile.open(fileName, fstream::in | fstream::binary);
	ioFile.read((char*)&isBin, sizeof(char)*4);
	ioFile.read((char*)&numPos, sizeof(int));
	ioFile.read((char*)&numWords, sizeof(int));
	if(isBin != testStr)
	{
		isThisBin = false;
		close();
		cout << "not bin" << endl;
	}
	cout << isBin << " " << numPos << " " << numWords << endl;
}

WordPack::WordPack(std::string fileName,int numPos, int numWords)
{
	char isBin[4] = "bin"; // 4 char lang pga. \0
	ioFile.open(fileName, fstream::out | fstream::binary);
	ioFile.write((char*)&isBin, sizeof(char)*4);
	ioFile.write((char*)&numPos, sizeof(int));
	ioFile.write((char*)&numWords, sizeof(int));
}

void WordPack::close()
{
	ioFile.close();
}


void WordPack::writeInt(int numWord)
{
	int highByte,lowByte;
	if(numWord<128)
	{
		ioFile << (unsigned char(numWord));
		highByte = numWord;
		lowByte = 0;
		//cout << highByte << " " << lowByte << endl;
	}
	else
	{
		highByte = (numWord/256);
		lowByte = numWord-(256*highByte);
		highByte += 128;
		//cout << highByte << " " << lowByte << endl;
		ioFile << (unsigned char(highByte)) << (unsigned char(lowByte));
	}
}
void WordPack::writeWord(std::string word)
{
	ioFile << char(word.length());
	for(int i=0;i<word.length();++i)
	{
		ioFile << word[i];
	}
}

std::string WordPack::getWord()
{
	char unsigned wordLength,thisChar;
	std::string word;
	wordLength = ioFile.get();
	for(int i=0;i<int(wordLength);++i)
	{
		thisChar = ioFile.get();
		word.push_back(thisChar);
	}
	//cout << "word=" << word << " wlength=" << int(wordLength) << endl;
	return word;
}

int WordPack::getInt()
{
	char unsigned hchar,lchar;
	int res=0;
	//ioFile >> hchar;
	hchar = ioFile.get();
	if(hchar<128)
	{
		res = int(hchar);
		//cout << "hchar " << int(hchar) << endl;
	}
	else
	{
		lchar = ioFile.get();
		hchar = hchar-128;
		//cout << "hchar " << int(hchar) << " lchar " << int(lchar) << endl;
		res = int((hchar * 256)) + int(lchar);
	}
	return res;
}

int WordPack::getNumPos()
{
	return numPos;
}

int WordPack::getNumWords()
{
	return numWords;
}

bool WordPack::getBin()
{
	return isThisBin;
}

WordPack::~WordPack(void)
{
}
